﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AddIn.EA.Framework;
using System.Xml;
using System.IO;
using AddIn.EA.Core.Common;

namespace AddIn.EA.Architecture.ComponentLogic
{
    public class CheckStructure
    {
        private List<string> Alert;

        private const string XmlFileName = "RuleStructurePackage.xml";

        public CheckStructure()
        {
            Alert = new List<string>();
        }

        public List<string> CheckPackage(Package package)
        {
            XmlDocument xml = this.GetXMLStructure();
            if (xml != null && xml.FirstChild != null & xml.FirstChild.NextSibling != null)
                this.CheckStructurePackage(package, xml.FirstChild.NextSibling);

            return Alert;
        }

        private void CheckStructurePackage(Package package, XmlNode node)
        {
            if (node != null)
            {
                package = this.CheckPackageEA(package, node.Name, GetIgnoreElement(node));

                if (package == null)
                    Alert.Add(node.ParentNode.Name + "." + node.Name);

                if (package != null)
                {
                    foreach (XmlNode item in node.ChildNodes)
                    {
                        this.CheckStructurePackage(package, item);
                    }
                }
            }
        }

        private Package CheckPackageEA(Package package, string name, bool IgnoreElement)
        {
            Package returnPackage = null;

            if (IgnoreElement)
            {
                if (package != null && package.Packages.Count > 0)
                    return package.Packages[0];
            }

            if (package != null)
            {
                returnPackage = package.Packages.Find(
                                                    delegate(Package pkg)
                                                    {
                                                        return pkg.Name == name;
                                                    });
                
            }

            return returnPackage;
        }

        private bool GetIgnoreElement(XmlNode node)
        {
            if (node.Attributes.Count > 0 && node.Attributes["IgnoreElement"] != null && node.Attributes["IgnoreElement"].Value.ToUpper() == "TRUE")
            {
                return true;
            }
            return false;
        }

        public XmlDocument GetXMLStructure()
        {
            string resourcesPath = Path.Combine(AddInRegistryResources.GetBaseDirectory(), "Resources");

            XmlDocument xml = new XmlDocument();
            xml.Load(Path.Combine(resourcesPath, XmlFileName));

            return xml;
        }
    }
}
